/**
 * 看板组件
 * 实现竖向分组、横向显示的看板布局
 */
class KanbanBoard {
    constructor(container) {
        this.container = container;
        this.demands = [];
        this.urgencyLevels = [];
        this.demandTypes = {};
        this.workflows = {};
        this.currentUser = null;
        
        this.init();
    }
    
    /**
     * 初始化看板
     */
    init() {
        this.container.innerHTML = `
            <div class="kanban-header">
                <div class="kanban-title">
                    <h2>需求看板</h2>
                    <div class="kanban-stats">
                        <span class="stat-item">
                            <span class="stat-label">总计:</span>
                            <span class="stat-value" id="total-demands">0</span>
                        </span>
                        <span class="stat-item">
                            <span class="stat-label">进行中:</span>
                            <span class="stat-value" id="active-demands">0</span>
                        </span>
                        <span class="stat-item">
                            <span class="stat-label">已完成:</span>
                            <span class="stat-value" id="completed-demands">0</span>
                        </span>
                    </div>
                </div>
                <div class="kanban-actions">
                    <button class="btn btn-primary" id="add-demand-btn">
                        <i class="icon">➕</i> 添加需求
                    </button>
                    <button class="btn btn-secondary" id="refresh-board-btn">
                        <i class="icon">🔄</i> 刷新
                    </button>
                </div>
            </div>
            
            <div class="kanban-filters">
                <div class="filter-group">
                    <label>需求类型:</label>
                    <select id="filter-type">
                        <option value="">所有类型</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>状态:</label>
                    <select id="filter-status">
                        <option value="">所有状态</option>
                        <option value="pending">待处理</option>
                        <option value="in_progress">进行中</option>
                        <option value="completed">已完成</option>
                        <option value="cancelled">已取消</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>负责人:</label>
                    <select id="filter-assignee">
                        <option value="">所有人</option>
                    </select>
                </div>
                <div class="filter-group">
                    <button class="btn btn-sm" id="clear-filters">清空筛选</button>
                </div>
            </div>
            
            <div class="kanban-board-container">
                <div class="kanban-columns" id="kanban-columns">
                    <!-- 动态生成列 -->
                </div>
            </div>
            
            <!-- 快速添加需求模态框 -->
            <div class="modal" id="quick-add-modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>快速添加需求</h3>
                        <button class="modal-close" id="quick-add-close">&times;</button>
                    </div>
                    <div class="modal-body">
                        <form id="quick-add-form">
                            <div class="form-group">
                                <label for="quick-title">标题 *</label>
                                <input type="text" id="quick-title" name="title" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="quick-description">描述</label>
                                <textarea id="quick-description" name="description" rows="3"></textarea>
                            </div>
                            
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="quick-type">类型 *</label>
                                    <select id="quick-type" name="type" required>
                                        <option value="">请选择</option>
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label for="quick-urgency">紧急度 *</label>
                                    <select id="quick-urgency" name="urgency" required>
                                        <option value="">请选择</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label for="quick-deadline">截止时间</label>
                                <input type="datetime-local" id="quick-deadline" name="deadline">
                            </div>
                            
                            <div class="form-actions">
                                <button type="button" class="btn btn-secondary" id="quick-add-cancel">取消</button>
                                <button type="submit" class="btn btn-primary">创建需求</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        `;
        
        this.setupEventListeners();
    }
    
    /**
     * 设置事件监听器
     */
    setupEventListeners() {
        // 添加需求按钮
        const addBtn = this.container.querySelector('#add-demand-btn');
        addBtn.addEventListener('click', () => this.showQuickAddModal());
        
        // 刷新按钮
        const refreshBtn = this.container.querySelector('#refresh-board-btn');
        refreshBtn.addEventListener('click', () => this.refresh());
        
        // 筛选器
        const filters = this.container.querySelectorAll('#filter-type, #filter-status, #filter-assignee');
        filters.forEach(filter => {
            filter.addEventListener('change', () => this.applyFilters());
        });
        
        // 清空筛选
        const clearFiltersBtn = this.container.querySelector('#clear-filters');
        clearFiltersBtn.addEventListener('click', () => this.clearFilters());
        
        // 快速添加模态框
        const modal = this.container.querySelector('#quick-add-modal');
        const closeBtn = this.container.querySelector('#quick-add-close');
        const cancelBtn = this.container.querySelector('#quick-add-cancel');
        const form = this.container.querySelector('#quick-add-form');
        
        closeBtn.addEventListener('click', () => this.hideQuickAddModal());
        cancelBtn.addEventListener('click', () => this.hideQuickAddModal());
        
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                this.hideQuickAddModal();
            }
        });
        
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleQuickAdd();
        });
    }
    
    /**
     * 加载数据
     */
    async loadData() {
        try {
            this.demands = await window.dataManager.getDemands();
            this.urgencyLevels = await window.dataManager.getUrgencyLevels();
            this.demandTypes = await window.dataManager.getDemandTypes();
            this.workflows = await window.dataManager.getWorkflows();
            
            // 获取当前用户
            this.currentUser = window.app.getCurrentUser();
            
            this.populateFilters();
            this.render();
        } catch (error) {
            console.error('加载看板数据失败:', error);
            window.app.showMessage('加载数据失败: ' + error.message, 'error');
        }
    }
    
    /**
     * 填充筛选器选项
     */
    populateFilters() {
        // 需求类型筛选
        const typeFilter = this.container.querySelector('#filter-type');
        typeFilter.innerHTML = '<option value="">所有类型</option>';
        Object.entries(this.demandTypes).forEach(([key, type]) => {
            if (type.enabled) {
                typeFilter.innerHTML += `<option value="${key}">${type.icon} ${type.name}</option>`;
            }
        });
        
        // 负责人筛选
        const assigneeFilter = this.container.querySelector('#filter-assignee');
        assigneeFilter.innerHTML = '<option value="">所有人</option>';
        const assignees = new Set();
        this.demands.forEach(demand => {
            if (demand.currentAssignee) {
                assignees.add(demand.currentAssignee);
            }
        });
        assignees.forEach(assignee => {
            assigneeFilter.innerHTML += `<option value="${assignee}">${assignee}</option>`;
        });
        
        // 填充快速添加表单选项
        const quickTypeSelect = this.container.querySelector('#quick-type');
        quickTypeSelect.innerHTML = '<option value="">请选择</option>';
        Object.entries(this.demandTypes).forEach(([key, type]) => {
            if (type.enabled) {
                quickTypeSelect.innerHTML += `<option value="${key}">${type.icon} ${type.name}</option>`;
            }
        });
        
        const quickUrgencySelect = this.container.querySelector('#quick-urgency');
        quickUrgencySelect.innerHTML = '<option value="">请选择</option>';
        this.urgencyLevels.forEach(level => {
            quickUrgencySelect.innerHTML += `<option value="${level.id}">${level.name}</option>`;
        });
    }
    
    /**
     * 渲染看板
     */
    render() {
        const filteredDemands = this.getFilteredDemands();
        
        // 更新统计信息
        this.updateStats(filteredDemands);
        
        // 按紧急度分组
        const groupedDemands = this.groupDemandsByUrgency(filteredDemands);
        
        // 渲染列
        const columnsContainer = this.container.querySelector('#kanban-columns');
        columnsContainer.innerHTML = '';
        
        this.urgencyLevels.forEach(urgencyLevel => {
            const demands = groupedDemands[urgencyLevel.id] || [];
            const column = this.createColumn(urgencyLevel, demands);
            columnsContainer.appendChild(column);
        });
    }
    
    /**
     * 获取筛选后的需求
     */
    getFilteredDemands() {
        const typeFilter = this.container.querySelector('#filter-type').value;
        const statusFilter = this.container.querySelector('#filter-status').value;
        const assigneeFilter = this.container.querySelector('#filter-assignee').value;
        
        return this.demands.filter(demand => {
            if (typeFilter && demand.type !== typeFilter) return false;
            if (statusFilter && demand.status !== statusFilter) return false;
            if (assigneeFilter && demand.currentAssignee !== assigneeFilter) return false;
            return true;
        });
    }
    
    /**
     * 按紧急度分组需求
     */
    groupDemandsByUrgency(demands) {
        const grouped = {};
        
        this.urgencyLevels.forEach(level => {
            grouped[level.id] = [];
        });
        
        demands.forEach(demand => {
            const urgencyId = demand.urgency || 1;
            if (grouped[urgencyId]) {
                grouped[urgencyId].push(demand);
            }
        });
        
        return grouped;
    }
    
    /**
     * 创建列
     */
    createColumn(urgencyLevel, demands) {
        const column = document.createElement('div');
        column.className = 'kanban-column';
        column.style.borderTopColor = urgencyLevel.color;
        
        column.innerHTML = `
            <div class="column-header">
                <div class="column-title">
                    <span class="urgency-indicator" style="background-color: ${urgencyLevel.color}"></span>
                    <span class="urgency-name">${urgencyLevel.name}</span>
                    <span class="demand-count">${demands.length}</span>
                </div>
                <button class="btn btn-sm btn-ghost add-to-column" data-urgency="${urgencyLevel.id}">
                    <i class="icon">➕</i>
                </button>
            </div>
            <div class="column-content" data-urgency="${urgencyLevel.id}">
                ${demands.map(demand => this.createDemandCard(demand)).join('')}
            </div>
        `;
        
        // 添加事件监听器
        const addBtn = column.querySelector('.add-to-column');
        addBtn.addEventListener('click', () => {
            this.showQuickAddModal(urgencyLevel.id);
        });
        
        return column;
    }
    
    /**
     * 创建需求卡片
     */
    createDemandCard(demand) {
        const demandType = this.demandTypes[demand.type] || {};
        const urgencyLevel = this.urgencyLevels.find(l => l.id === demand.urgency) || {};
        
        // 计算进度
        const progress = this.calculateProgress(demand);
        
        // 格式化时间
        const createdDate = new Date(demand.createdAt).toLocaleDateString();
        const deadlineDate = demand.deadline ? new Date(demand.deadline).toLocaleDateString() : '';
        
        // 状态显示
        const statusText = this.getStatusText(demand.status);
        const statusClass = `status-${demand.status}`;
        
        return `
            <div class="demand-card" data-demand-id="${demand.id}">
                <div class="card-header">
                    <div class="card-type">
                        <span class="type-icon">${demandType.icon || '📋'}</span>
                        <span class="type-name">${demandType.name || '未知类型'}</span>
                    </div>
                    <div class="card-actions">
                        <button class="btn-icon edit-demand" data-demand-id="${demand.id}" title="编辑">
                            <i class="icon">✏️</i>
                        </button>
                        <button class="btn-icon delete-demand" data-demand-id="${demand.id}" title="删除">
                            <i class="icon">🗑️</i>
                        </button>
                    </div>
                </div>
                
                <div class="card-content">
                    <h4 class="demand-title">${demand.title}</h4>
                    ${demand.description ? `<p class="demand-description">${demand.description}</p>` : ''}
                    
                    <div class="demand-meta">
                        <div class="meta-item">
                            <span class="meta-label">状态:</span>
                            <span class="meta-value ${statusClass}">${statusText}</span>
                        </div>
                        
                        ${demand.currentAssignee ? `
                            <div class="meta-item">
                                <span class="meta-label">负责人:</span>
                                <span class="meta-value">${demand.currentAssignee}</span>
                            </div>
                        ` : ''}
                        
                        <div class="meta-item">
                            <span class="meta-label">创建时间:</span>
                            <span class="meta-value">${createdDate}</span>
                        </div>
                        
                        ${deadlineDate ? `
                            <div class="meta-item">
                                <span class="meta-label">截止时间:</span>
                                <span class="meta-value ${this.isOverdue(demand.deadline) ? 'overdue' : ''}">${deadlineDate}</span>
                            </div>
                        ` : ''}
                    </div>
                    
                    ${progress.total > 0 ? `
                        <div class="progress-section">
                            <div class="progress-header">
                                <span class="progress-label">进度</span>
                                <span class="progress-text">${progress.completed}/${progress.total}</span>
                            </div>
                            <div class="progress-bar">
                                <div class="progress-fill" style="width: ${progress.percentage}%"></div>
                            </div>
                        </div>
                    ` : ''}
                </div>
                
                <div class="card-footer">
                    <div class="card-tags">
                        ${demand.tags ? demand.tags.map(tag => `<span class="tag">${tag}</span>`).join('') : ''}
                    </div>
                    
                    <div class="card-priority">
                        <span class="priority-indicator" style="background-color: ${urgencyLevel.color}" title="${urgencyLevel.name}"></span>
                    </div>
                </div>
            </div>
        `;
    }
    
    /**
     * 计算需求进度
     */
    calculateProgress(demand) {
        if (!demand.workflow || !demand.workflow.nodes) {
            return { completed: 0, total: 0, percentage: 0 };
        }
        
        const total = demand.workflow.nodes.length;
        const completed = demand.workflow.nodes.filter(node => node.status === 'completed').length;
        const percentage = total > 0 ? Math.round((completed / total) * 100) : 0;
        
        return { completed, total, percentage };
    }
    
    /**
     * 获取状态文本
     */
    getStatusText(status) {
        const statusMap = {
            'pending': '待处理',
            'in_progress': '进行中',
            'completed': '已完成',
            'cancelled': '已取消'
        };
        return statusMap[status] || '未知';
    }
    
    /**
     * 检查是否逾期
     */
    isOverdue(deadline) {
        if (!deadline) return false;
        return new Date(deadline) < new Date();
    }
    
    /**
     * 更新统计信息
     */
    updateStats(demands) {
        const total = demands.length;
        const active = demands.filter(d => d.status === 'in_progress').length;
        const completed = demands.filter(d => d.status === 'completed').length;
        
        this.container.querySelector('#total-demands').textContent = total;
        this.container.querySelector('#active-demands').textContent = active;
        this.container.querySelector('#completed-demands').textContent = completed;
    }
    
    /**
     * 应用筛选器
     */
    applyFilters() {
        this.render();
    }
    
    /**
     * 清空筛选器
     */
    clearFilters() {
        this.container.querySelector('#filter-type').value = '';
        this.container.querySelector('#filter-status').value = '';
        this.container.querySelector('#filter-assignee').value = '';
        this.render();
    }
    
    /**
     * 显示快速添加模态框
     */
    showQuickAddModal(urgencyId = null) {
        const modal = this.container.querySelector('#quick-add-modal');
        const form = this.container.querySelector('#quick-add-form');
        
        // 重置表单
        form.reset();
        
        // 如果指定了紧急度，预选择
        if (urgencyId) {
            this.container.querySelector('#quick-urgency').value = urgencyId;
        }
        
        modal.style.display = 'flex';
        
        // 聚焦到标题输入框
        setTimeout(() => {
            this.container.querySelector('#quick-title').focus();
        }, 100);
    }
    
    /**
     * 隐藏快速添加模态框
     */
    hideQuickAddModal() {
        const modal = this.container.querySelector('#quick-add-modal');
        modal.style.display = 'none';
    }
    
    /**
     * 处理快速添加
     */
    async handleQuickAdd() {
        const form = this.container.querySelector('#quick-add-form');
        const formData = new FormData(form);
        
        const demand = {
            title: formData.get('title').trim(),
            description: formData.get('description').trim(),
            type: formData.get('type'),
            urgency: parseInt(formData.get('urgency')),
            deadline: formData.get('deadline') || null,
            status: 'pending',
            submitter: this.currentUser ? this.currentUser.name : '匿名用户',
            submitterId: this.currentUser ? this.currentUser.id : null
        };
        
        // 验证必填字段
        if (!demand.title || !demand.type || !demand.urgency) {
            window.app.showMessage('请填写所有必填字段', 'error');
            return;
        }
        
        try {
            // 显示加载状态
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            submitBtn.textContent = '创建中...';
            submitBtn.disabled = true;
            
            // 创建需求
            const result = await window.dataManager.addDemand(demand);
            
            if (result.success) {
                window.app.showMessage('需求创建成功', 'success');
                this.hideQuickAddModal();
                await this.refresh();
            } else {
                window.app.showMessage('创建失败: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('创建需求失败:', error);
            window.app.showMessage('创建失败: ' + error.message, 'error');
        } finally {
            // 恢复按钮状态
            const submitBtn = form.querySelector('button[type="submit"]');
            submitBtn.textContent = '创建需求';
            submitBtn.disabled = false;
        }
    }
    
    /**
     * 刷新看板
     */
    async refresh() {
        try {
            await this.loadData();
            window.app.showMessage('看板已刷新', 'success');
        } catch (error) {
            console.error('刷新看板失败:', error);
            window.app.showMessage('刷新失败: ' + error.message, 'error');
        }
    }
    
    /**
     * 设置当前用户
     */
    setCurrentUser(user) {
        this.currentUser = user;
    }
}

// 导出类
window.KanbanBoard = KanbanBoard;